package com.hqd.ch03.v26.beans;

import com.hqd.ch03.v26.beans.property.support.AbstractPropertyAccessor;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWrapper {

    private Object bean;

    public BeanWrapperImpl(Object bean, Class<?> beanClass) {
        super(beanClass);
        this.bean = bean;
    }

    @Override
    public Object getWrappedInstance() {
        return bean;
    }

    @Override
    public Class<?> getWrappedClass() {
        return clazz;
    }

    @Override
    public boolean isReadableProperty(String propertyName) {
        return false;
    }

    @Override
    public boolean isWritableProperty(String propertyName) {
        return false;
    }

    @Override
    public Object getPropertyValue(String propertyName) {
        try {
            PropertyDescriptor pd = new PropertyDescriptor(propertyName, clazz);
            return pd.getReadMethod().invoke(bean);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public void setPropertyValue(String propertyName, Object value) {
        Object newVal = value;
        Class<?> propertyType = getPropertyType(propertyName);
        newVal = convertIfNecessary(value, propertyType);
        try {
            PropertyDescriptor pd = new PropertyDescriptor(propertyName, clazz);
            Method methodName = pd.getWriteMethod();
            methodName.invoke(bean, newVal);
        } catch (Exception e) {
            throw new RuntimeException("set value [" + value + "] into property [" + propertyName + "] error. the bean is [" + clazz.getName());
        }
    }
}
